#include "queue.h"

void QueueInit(Queue* q)
{
	assert(q);
	q->_front = NULL;
	q->_rear = NULL;
	q->size = 0;
}

void QueuePush(Queue* q, QDataType data)
{
	assert(q);
	QNode* cur = (QNode*)malloc(sizeof(QNode));
	if (cur == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	cur->_data = data;
	cur->_next = NULL;
	if (q->size == 0)
	{
		q->_front = q->_rear = cur;
	}
	else
	{
		q->_rear->_next = cur;
		q->_rear = cur;
	}
	q->size++;
}

void QueuePop(Queue* q)
{
	assert(q);
	assert(q->size);
	QNode* cur = q->_front->_next;
	free(q->_front);
	q->_front = cur;
	q->size--;
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(q->size);
	return q->_front->_data;
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(q->_rear);
	return q->_rear->_data;
}

int QueueSize(Queue* q)
{
	assert(q);
	return q->size;
}

bool QueueEmpty(Queue* q)
{
	assert(q);
	if (q->size == 0)
	{
		return true;
	}
	return false;
}

void QueueDestroy(Queue* q)
{
	assert(q);
	while (q->_front != q->_rear)
	{
		QNode* next = q->_front->_next;
		free(q->_front);
		q->_front = next;
	}
	free(q->_front);
	q->_front = q->_rear = NULL;
}

void Print(Queue* q)
{
	assert(q);
	QNode* cur = q->_front;
	while (cur)
	{
		printf("%d->", cur->_data);
		cur = cur->_next;
	}
	printf("NULL\n");
}
